<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2023/5/9
 * Time: 11:13
 */

namespace fast;

use fast\Hashids\Hashids;

class IDUtil
{
    public static $map = [];

    private static function _getHashIds($type = 'default')
    {
//        if ($type == 'news') {
//            if (self::$newsHashIds == null) {
//                $idEncodeSalt = config('news_id_encode_salt');
//                $hashIds = new Hashids($idEncodeSalt);
//                self::$newsHashIds = $hashIds;
//            }
//            return self::$newsHashIds;
//        } else {
//            if (self::$hashIds == null) {
//                $idEncodeSalt = config('id_encode_salt');
//                $hashIds = new Hashids($idEncodeSalt);
//                self::$hashIds = $hashIds;
//            }
//            return self::$hashIds;
//        }
        if (isset(self::$map[$type]) && self::$map[$type]) {
            return self::$map[$type];
        } else {
//            $idEncodeSalt = config($type . '_id_encode_salt');
            $idEncodeSalt = '27AB50F22AB2438EAFAD5A4E9DDC52880673C7019F7245738187B2D16F15C920';
            $hashIds = new Hashids($idEncodeSalt);

            self::$map[$type] = $hashIds;
            return $hashIds;
        }

    }

    /**
     * id加密
     * @param $id
     */
    public static function encode($id)
    {
        $hashIds = self::_getHashIds();
        return $hashIds->encode($id);
    }

    /**
     * id 解密
     * @param $id
     * @return array
     */
    public static function decode($id)
    {
        $hashIds = self::_getHashIds();
        $res = $hashIds->decode($id);
        if ($res) {
            return $res[0];
        }
        return null;
    }

    public static function encodeContent($id)
    {
        $hashIds = self::_getHashIds('news');
        return $hashIds->encode($id);
    }

    public static function decodeContent($id)
    {
        $hashIds = self::_getHashIds('news');
        $res = $hashIds->decode($id);
        if ($res) {
            return $res[0];
        }
        return null;
    }

    public static function encodeActivity($id)
    {
        $hashIds = self::_getHashIds('activity');
        return $hashIds->encode($id);
    }

    public static function decodeActivity($id)
    {
        $hashIds = self::_getHashIds('activity');
        $res = $hashIds->decode($id);
        if ($res) {
            return $res[0];
        }
        return null;
    }
}